﻿/*
*************************************
**
**      Program by HuShua soft.
**
*************************************
*/

Number.prototype.toFixed = function(d){
	var s = this + "";
	if(!d || d<0) d = 0;
	if(s.indexOf(".") == -1) s += "."; 
	s += new Array(d + 1).join("0");
	if(new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+ (d + 1) +"})?)\\d*$").test(s)){
		var s = "0" + RegExp.$2;
		var pm = RegExp.$1;
		var a = RegExp.$3.length;
		var b = true;
		if(a == d + 2){
			a = s.match(/\d/g);
			if(parseInt(a[a.length - 1]) > 4){
				for(var i = a.length-2; i>=0; i--){
					a[i] = parseInt(a[i]) + 1;
					if(a[i] == 10){
						a[i] = 0; b = i!= 1;
					} else {
						break;
					}
				}
			}
			s = a.join("").replace(new RegExp("(\\d+)(\\d{"+ d +"})\\d$"), "$1.$2");
		}
		if(b){
			s = s.substr(1);
		}
		return (pm+s).replace(/\.$/, "");
	} 
	return this + "";
}; 

String.prototype.AsDate = function(){
	if(!this.IsDate()) return (new Date());
	var d = eval('new Date(' + this.replace(/\d+(?=-[^-]+$)/, function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
	return d;
}

String.prototype.IsDate = function(){
	if(this == null) return false;	
	var _regDate = this.match(/^(\d{1,4})(-|\/|\.)(\d{1,2})\2(\d{1,2})$/); 
	var _regDateTime = this.match(/^(\d{1,4})(-|\/|\.)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
	if(_regDate == null && _regDateTime == null) return false;
	if(_regDate){
		var d = new Date(_regDate[1], _regDate[3] - 1, _regDate[4]); 
		return (d.getFullYear() == _regDate[1] && (d.getMonth()+1) == _regDate[3] && d.getDate() == _regDate[4]);
	}
	if(_regDateTime){		
		var t = new Date(_regDateTime[1], _regDateTime[3] - 1, _regDateTime[4], _regDateTime[5], _regDateTime[6], _regDateTime[7]);
		return (t.getFullYear() == _regDateTime[1] && (t.getMonth()+1) == _regDateTime[3] && t.getDate() == _regDateTime[4] && t.getHours() == _regDateTime[5] && t.getMinutes() == _regDateTime[6] && t.getSeconds() == _regDateTime[7]);
	}
}

String.prototype.Trim = function(){
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.IsNull = function(){	
	return !this || this.Trim() == "";
}

String.prototype.Join = function(str, sp){
    if(this.Trim() == "") return str;
    if(str.Trim() == "") return this;
    if(sp){
       return (this + sp + str);
    }else{
       return (this + "," + str);
    }
}

String.prototype.IsImage = function(){
    var strImageExt = ".jpeg|.gif|.jpg|.png|.bmp|.pic|"
    if(this.indexOf(".")>-1){
        var p = this.lastIndexOf(".");
        var ext = this.substring(p, this.length) + '|';        
        ext = ext.toLowerCase();
        if(strImageExt.indexOf(ext) > -1){
            return true;
        }
    }
    return false;  
}

String.prototype.ImageThumb = function(){
   if(!this.IsImage()) return this;
   var p = this.lastIndexOf(".");
   var ext = this.substring(p, this.length);
   var f = this.substring(0, p);
   return (f + "_s" + ext);
}

String.prototype.Encode = function(){
	var str = escape(this);
	str = str.replace(/\+/g, "%2B");
    str = str.replace(/\&/g, "%26");
	return str;
}

String.prototype.IsNumber = function(){
	var reg = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	var str = this.Trim();
	return reg.test(str);
}

String.prototype.ToNumber = function(){
	var str = this.Trim();
	if(str.IsNumber()){
		return parseFloat(str);		 
	}else{
		if(arguments[0]){
			return arguments[0];
		}
		return 0;
	}
}

Date.prototype.AsString = function(format){
	var data = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(),     //day
		"h+" : this.getHours(),    //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter
		"S" : this.getMilliseconds() //millisecond
	}
	if(!format || format.Trim() == "") format = "yyyy-MM-dd";
	if(/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in data) {
		if(new RegExp("("+ k +")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? data[k] : ("00" + data[k]).substr(("" + data[k]).length));
		}
	}
	return format;
}

Array.prototype.AsString = function(s){
	var str = "";
	for(var i=0; i<this.length; i++){
		if(i > 0){
			str += "," + this[i];
		}else{
			str += this[i];
		}
	}
}

Array.prototype.IndexOf = function(s){
    for(var i=0; i<this.length; i++){
        if(this[i].toString().toLowerCase() == s.toString().toLowerCase()) return i;
    }
    return -1;
}

function BindWindowEvent(eventName, eventArgs){
	if(window.attachEvent){
		window.attachEvent("on" + eventName, eventArgs);
	}else{
		window.addEventListener(eventName, eventArgs, false);
	}	
}

function StopReturnEvent(event){
    try {        
        event.returnValue = false; //IE
        event.preventDefault(); //FF
        Event.stop(event);
    } catch(ex){
    }
}

function $frame(id){
   return document.frames ? document.frames(id) : document.getElementById(id).contentWindow;            
}

function KeyCode(event){
    return event ? event.keyCode : event.which;
}

function ClearOptions(object){
	if(!object || !object.options) return false;	
    while(object.options.length > 0){
        object.options[object.options.length - 1] = null;
    }
}

function PageBack(url){
    if(!url){
        window.history.back();
    }else{
        window.location.href = url;
    }
    return false;
}

function LoadIframe(iframe, url, display, callback){    
    var frame = $(iframe);
    if(!frame) return; 
	if(!frame.loader){
	    var loader = document.createElement("div");
		var img = document.createElement("img");
		loader.id = frame.id + "_loader";
		loader.style.margin = "20px";
		loader.style.textAlign = "center";
		img.src = "/images/loading32.gif";
		img.border = "0";
		loader.appendChild(img);
		loader.style.display = "none";
		frame.parentNode.insertBefore(loader, frame.nextSibling);		
		frame.loader = loader.id;	
	}	
	if(url) $frame(iframe).location = url;
	frame.hide();
	
	var loading = $(frame.loader);
	loading.show();
	if(Prototype.Browser.IE){
        frame.onreadystatechange = function(){     
            if(this.readyState == "complete"){
                loading.hide();
                frame.show();
                if(callback) setTimeout(callback, 1);
            }
        };
    } else {
        frame.onload = function(){            
            frame.show();
            loading.hide();   
            if(callback) setTimeout(callback, 1);
        };
    }
    
    
    frame.completed = function(){
	    frame.onreadystatechange = null;
	    frame.onload = null;
	    loading.show();
	    frame.hide();
	};
	
	frame.reset = function(){
	    loading.hide();
	    frame.show();
	}
}

function DateAdd(interval, num, date){
    var yyyy = date.getFullYear();
	var mm = date.getMonth() + 1;
	var dd = date.getDate();
	var dt = (yyyy +"-"+ mm +"-"+ dd).AsDate();
	switch(interval){
	    case "y":
		    return new Date(dt.setYear(dt.getFullYear() + num));
			break;
		case "m":
		    return new Date(dt.setMonth(dt.getMonth() + num));
			break;
		case "d":
		    return new Date(dt.setDate(dt.getDate() + num));
		    break;
	}
}

function DateDiff(interval, d1, d2){
	var t1 = d1.getTime(), t2 = d2.getTime(), i={};
	i["y"] = d2.getFullYear() - d1.getFullYear();
	i["m"] = i["y"]*12 + d2.getMonth() - d1.getMonth();
	i["d"] = Math.floor(t2/86400000) - Math.floor(t1/86400000);
	return i[interval];
}

function BindTabEvent(){
    if(!$("tab")) return;
	var tab = $("tab").getElementsByTagName("li");	
	if(!tab) return;
	for(var i=0;i<tab.length;i++){		
		tab[i].index = i;
		tab[i].onclick = function(){			
			ShowTab(this.index);
		};
		BindTabContentEvents(i, "textarea");
		BindTabContentEvents(i, "input");
		BindTabContentEvents(i, "select");
	}
}

function BindTabContentEvents(index, tag){
	var content = $("tab_content_" + index);
	var input = content.getElementsByTagName(tag);
	for(var i=0; i<input.length; i++){
		Event.observe(input[i], "focus", function(){ ShowTab(index) });
	}
}

function ShowTab(n){	
	var tab = $("tab").getElementsByTagName("li");
	for(var i=0;i<tab.length;i++){
		tab[i].className = (i == n) ? "actived" : "";
		if($("tab_content_"+ i)){
			$("tab_content_"+ i).style.display = (i == n) ? "" : "none";
		}
	}
}

function HideTab(n){
    var tab = $("tab").getElementsByTagName("li");
    if(n < tab.length){
        tab[n].style.display = "none";
    }
}

/* FF 相关 */
function FireFoxExplorer(){
	if(Prototype.Browser.IE) return;
    window.constructor.prototype.__defineGetter__("event", function(){ return(__window_event_constructor()); }); 
    Event.prototype.__defineGetter__("srcElement", function(){  return this.target;  }); 
	
	var links = document.getElementsByTagName("a");
    var inputs = document.getElementsByTagName("input");
    for(var i = 0; i < links.length; i++){
        if(links[i].getAttribute("disabled")){
            links[i].className = "disabled";
        }
    }
    for(var i = 0; i < inputs.length; i++){
        if(inputs[i].getAttribute("disabled")){
            inputs[i].className = "disabled";
        }
    }
}

function __window_event_constructor(){ 
    if(Prototype.Browser.IE) return(window.event);
    var _caller = __window_event_constructor.caller; 
    while(_caller!=null){
        var _argument=_caller.arguments[0]; 
        if(_argument){ 
            var _temp=_argument.constructor;
            if(_temp.toString().toLowerCase().indexOf("event")!=-1)
                return(_argument); 
        }
        _caller=_caller.caller; 
    }
    return(null);
}

BindWindowEvent("load", FireFoxExplorer);
BindWindowEvent("load", BindTabEvent);



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


var HuShua = {};

HuShua.UI = {
    PageLoader : {
	    ElementCreated : false,
	    Init : function(){		
		    var documentBody = $$("body")[0];
		    documentBody.appendChild(
						    Builder.node('div', { id: "HuShuaWebLoading", style: "text-align:center; position:absolute; background:#fff; z-index:99999999; font-family:Arial; " })
					    );
		    this.handle = $("HuShuaWebLoading");
		    this.handle.setStyle({ width: this.params.width + "px", height: (this.params.height / 2) + "px", paddingTop: (this.params.height / 2 - 50) + "px" }).hide();
		    this.handle.update(this.params.icon + "<br /> Loading ......");
		    this.ElementCreated = true;
		    return this;
	    },
    	
	    Show : function(){
		    var defaults = {width: 350, height: 200, icon: "<div class='loading'><img src='/Images/loading32.gif' border='0' /></div>", make: true }
		    this.params = Object.extend(defaults, arguments[0] || { });
		    if(!this.ElementCreated){
			    this.Init();
		    }
		    this.Resize();
		    this.eventResize    = this.Resize.bindAsEventListener(this);
		    Event.observe(window, "resize", this.eventResize);
		    return this;
	    },
    	
	    Resize : function(){
		    var pageScroll = document.viewport.getScrollOffsets();
		    var left = (document.viewport.getWidth() - this.params.width) / 2;
		    var top = pageScroll.top + (document.viewport.getHeight() - this.params.height)  / 2;
    		
		    if(this.params.make) HuShua.UI.Make.Show();
		    if(this.handle) this.handle.setStyle({ left: left + "px", top: top + "px" }).show();
	    },
    	
	    Hide : function(){
		    HuShua.UI.Make.Hide();
		    if(this.handle) this.handle.hide();
		    if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
	    }
    },
    
    Make : {
		div : null,
		Show : function(){
			if(!this.div){
				var documentBody = $$('body')[0];
				documentBody.appendChild(
						Builder.node('div', { id: "HuShuaWebMake" })
					);
				this.div = $("HuShuaWebMake");
				this.div.setStyle({left: "0px", top: "0px", position: "absolute", width: "100%", background: "#333", zIndex: 550});
			}
			var pageSize = HuShua.UI.GetPageSize();
			this.div.setStyle({height: pageSize.height + "px", opacity: .5}).show();
			HuShua.UI.HideSelects();
		},
		
		Hide : function(){
			if(this.div){
				try{
					new Effect.Fade(this.div, { duration: 0.2 });
				}catch(ex){
					this.div.hide();
				}
			}
			HuShua.UI.ShowSelects();
		}
	},
	
	GetPageSize : function(){
		var pageScroll = HuShua.UI.GetPageScroll();
		var windowWidth, windowHeight;
		if (self.innerHeight) {
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		
		if(pageScroll.top < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = pageScroll.top;
		}
		
		if(pageScroll.left < windowWidth){
			pageWidth = pageScroll.left;
		} else {
			pageWidth = windowWidth;
		}
		return {width:pageWidth, height:pageHeight};
	},
	
	GetPageScroll : function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else {
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		return {left: xScroll, top: yScroll}
	},
	
	CreateElement : function(){
		var params = arguments[0];
		if(!params.element) params.element = "div";
		var element = document.createElement(params.element);
		if(params.id) { element.id = params.id; element.name = params.id; }
		if(params.className) element.className = params.className;
		if(params.text) element.innerHTML = params.text;
		return element;
	},
	
	RemoveElement : function(node){
		for(var i = node.childNodes.length - 1; i >= 0; i--){
			node.removeChild(node.childNodes[i]);
		}
	},
	
	GetElementOffsets : function(element){
		var top = element.offsetTop;  
		var left = element.offsetLeft;
		while(element = element.offsetParent){
			top += element.offsetTop + (Prototype.Browser.IE ? element.clientTop : 0);
			left += element.offsetLeft + (Prototype.Browser.IE ? element.clientLeft : 0);
		} 
		return {top: top, left: left};	
	},
	
	HideSelects : function(){
		if(this.IE6() == true){
			var selects = document.getElementsByTagName("select");
			for(var i = 0; i < selects.length; i++){
				selects[i].style.display = "none";
			}
		}
	},
	
	ShowSelects : function(){
		if(this.IE6() == true){
			var selects = document.getElementsByTagName("select");
			for(var i = 0; i < selects.length; i++){
				selects[i].style.display = "";
			}
		}
	},
	
	IE6 : function(){
		if(Prototype.Browser.IE && (window.navigator.appVersion.indexOf("MSIE 6.0") > -1 || window.navigator.appVersion.indexOf("MSIE 5.0") > -1)){
			return true;
		}else{
		    return false;
		}
	}
}

HuShua.UI.Tips = {
	ElementCreated : false,
	IsOver : false,
	defaults : {
		width : 450,
		title : "Web Tips",
		content : ""
	},
	
	Show : function(){
		var me = this;
		if(event) Event.stop(event);
		this.eventHide   = this.Hide.bindAsEventListener(this);
		this.eventResize = this.Resize.bindAsEventListener(this);
		
		if(this.ElementCreated == false || !this.handle){
			var documentBody = $$('body')[0];
			documentBody.appendChild(
					Builder.node('div', { id: "HuShuaWebTips", "class": "tips" }, [
						    Builder.node("div", { id: "HuShuaWebTips_top", "class": "tips_top" }),
							Builder.node("div", { id: "HuShuaWebTips_head", "class": "tips_head" }, [
									Builder.node("div", { id: "HuShuaWebTips_btnClose", "class": "tips_close" }),
									Builder.node("div", { id: "HuShuaWebTips_title", "class": "tips_title" })
							]),
							Builder.node("div", { id: "HuShuaWebTips_panel", "class": "tips_panel" }, 
									Builder.node("div", { id: "HuShuaWebTips_body", "class": "tips_body" })
							)
					])
				);	
			this.handle = $("HuShuaWebTips");
			this.top = $("HuShuaWebTips_top");
			this.head = $("HuShuaWebTips_head");
			this.title = $("HuShuaWebTips_title");
			this.btnClose = $("HuShuaWebTips_btnClose");
			this.body = $("HuShuaWebTips_body");
			
			Event.observe(this.btnClose, "click", function(){ me.IsOver = false; });
			this.ElementCreated = true;
		}
		if(!this.handle) return;		
		this.params = Object.extend(this.defaults, arguments[0] || { });		
		
		this.title.update(this.params.title);
		this.body.update(this.params.content);	
		this.target = event.target || event.srcElement; 
		this.Resize();
						
		Event.observe(document, "click", this.eventHide);		
		Event.observe(this.handle, "mousemove", function(){ me.IsOver = true; });
		Event.observe(this.handle, "mouseout", function(){ me.IsOver = false; });
		//Event.observe(window, "resize", this.eventResize);
		return this;
	},
	
	Resize : function(){
		this.topX = this.params.width * .25;
		this.x = 100; // left
		this.y = 100; // top
		
		var pageScroll = document.viewport.getScrollOffsets();	
		if(this.target){
			var p = HuShua.UI.GetElementOffsets(this.target);	
			var targetX = p.left - this.target.offsetWidth / 2;
			if(targetX < document.body.clientWidth / 2){
				this.topX = this.params.width * .25;
			}else{
				this.topX = this.params.width * .75;
			}			
			this.x = p.left - this.topX + this.target.offsetWidth / 2;
			this.y = p.top + this.target.offsetHeight;
			
			if(this.x + this.params.width > document.body.clientWidth){
				this.topX += this.x - (document.body.clientWidth - this.params.width - 10);
				this.x = document.body.clientWidth - this.params.width - 10;
			}else if(this.x < 10){
				this.topX -= 10 - this.x;
				this.x = 10;				
			}
		}
		this.top.setStyle({ backgroundPosition: this.topX +"px top" });
		this.handle.setStyle({ width: this.params.width +"px", top: this.y +"px", left: this.x +"px" }).show();
		return this;
	},
	
	Loading : function(){
		this.body.update("<div class='loading'><img src='/Images/loading32.gif' border='0' /></div>");
		return this;
	},
	
	Update : function(content){
		this.body.update(content);
		return this;
	},
	
	Hide : function(){
		if(this.handle && !this.IsOver){
			this.handle.hide();
			this.IsOver = false;
			this.target = null;
			if(this.eventHide) Event.stopObserving(document, "click", this.eventHide);
			//if(this.eventResize) Event.stopObserving(window, "resize", this.eventResize);
		}		
		return this;
	}
}

HuShua.JSON = {
    toJson : function(str){
        if(!str) return null;
        var text = str.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        return eval("("+ text +")");
    },
    
    toString : function(obj){
        switch(typeof(obj)){
            case 'object':
                var ret = [];
                if (obj instanceof Array){
                    for (var i = 0, len = obj.length; i < len; i++){
                        ret.push(JSON.toString(obj[i]));
                    }
                    return '[' + ret.join(',') + ']';
                }else if (obj instanceof RegExp){
                    return obj.toString();
                }else{
                    for (var a in obj){
                        ret.push(a + ':' + JSON.toString(obj[a]));
                    }
                    return '{' + ret.join(',') + '}';
                }
            case 'function': return 'function() {}';
            case 'number': return obj.toString();
            case 'string': return "\"" + obj.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function(a) {return ("\n"==a)?"\\n":("\r"==a)?"\\r":("\t"==a)?"\\t":"";}) + "\"";
            case 'boolean': return obj.toString();
            default: return obj.toString();
        }
    }
};